#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <string.h>
#include <fcntl.h>

void child(char *argv[])
{
	int fd;
	if(argv[1] != NULL && argv[1][0] == '<') {
		fd = open(strtok(argv[1], "<"), O_CREAT|O_RDONLY, 0666);
		dup2(fd, 0);
		close(fd);
		argv[1] = NULL;	
	}
	else if(argv[2] != NULL && argv[2][0] == '>') {
		if(argv[2][1] == '>')
			fd = open(strtok(argv[2], ">"), O_CREAT|O_WRONLY|O_APPEND, 0666);
		else 	
			fd = open(strtok(argv[2], ">"), O_CREAT|O_WRONLY|O_TRUNC, 0666);
		dup2(fd, 1);
		close(fd);
		argv[2] = NULL;
	}	
}

void sh2(char *command)
{
	char buffer[100];
	char item[10][20];
	char *word;
	char *argv[5];
	strcpy(buffer, command);
	word = strtok(buffer, " ");
	int i = 0, j;
	while(word != NULL) {
		strcpy(item[i++], word);
		word = strtok(NULL, " ");
	}
	for(j=0; j<i; ++j) {
		argv[j] = (char *)malloc(sizeof(char)*20);
		strcpy(argv[j], item[j]);
	}
	argv[j] = NULL;
	if(strcmp(argv[0], "cd") == 0) {
		chdir(argv[1]);
	}
	else if(strcmp(argv[0], "pwd") == 0) {
		char dir[100];
		getcwd(dir, sizeof(dir));
		printf("%s\n", dir);
	}
	else if(strcmp(argv[0], "exit") == 0) {
		exit(0);
	}
	else{
		pid_t pid;
		pid = fork();
		if(pid == 0) {
			child(argv);
			int error = execvp(argv[0], argv);
			if(error < 0) {
				perror("execvp");
			}
			exit(127);
		}
		wait(NULL);
	}
	for(j=0; j<i; ++j) {
		free(argv[j]);
	}
}

int main()
{
    char line[100];
    int c;
    while(1) {
    	printf(">");
    	fflush(stdout);
	    fgets(line, sizeof(line), stdin);  
		line[strlen(line)-1] = '\0';  
		sh2(line);            
	}
    return 0;
}
